I'm trying to apply conditional styles in React. I need to apply an animation when use click on delete button but this is applied to every element from the array
Component
import React, { useState } from 'react';
import './styles.css';
const Element = () => {
const [onDelete, setOnDelete] = useState(false);
const list = [
{
name: 'Jhon',
age: '20',
},
{
name: 'Maria',
age: '25',
},
];
return (
<>
{list.map((item) => (
<ul className={onDelete ? 'onDelete-apply' : ''}>
<li>{item.name}</li>
<li>{item.age}</li>
<button onClick={() => setOnDelete(true)}>
Delete
</button>
</ul>
))}
</>
);
};
export default Element;
Styles
.onDelete-apply {
background-color: red;
}
*For example in this component i want to apply red background only to the clicked element *
You should be traking the element that it is clicked by its index, insted of true or false, on click you set the index of the clicked item in the state and then check if that index is the same as the index of the element when rendered
import React, { useState } from 'react';
import './styles.css';
const Element = () => {
const [deletedIndex, setDeletedIndex] = useState(false);
const list = [
{
name: 'Jhon',
age: '20',
},
{
name: 'Maria',
age: '25',
},
];
return (
<>
{list.map((item, i) => (
<ul key={i} className={deletedIndex === i ? 'onDelete-apply' : ''}>
<li>{item.name}</li>
<li>{item.age}</li>
<button onClick={() => setDeletedIndex(i)}>Delete</button>
</ul>
))}
</>
);
export default Element;